package com.sp.interceptor;

import com.google.gson.Gson;
import com.sp.system.user.core.annotation.NotAuthentication;
import com.sp.system.user.core.exception.TokenVerifyException;
import com.sp.system.user.core.utils.BaseResult;
import com.sp.system.user.core.utils.enums.PermissionEnum;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * tonken 校验
 */
@Component
public class TokenInterceptor extends HandlerInterceptorAdapter {

    /**
     * token参数头
     */
    public static String tokenHeader;


    @Value("${jwt.tokenHeader}")
    public void setTokenHeader(String tokenHeader) {
        this.tokenHeader = tokenHeader;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        try {
            // 如果打了该注解是表示不需要进行登陆认证的的，直接放行
//            NotAuthentication notAuthentication = ((HandlerMethod) handler).getMethodAnnotation(NotAuthentication.class);
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();

            NotAuthentication notAuthentication = method.getAnnotation(NotAuthentication.class);
            if (notAuthentication != null) {
                return super.preHandle(request, response, handler);
            }
            notAuthentication = method.getDeclaringClass().getAnnotation(NotAuthentication.class);
            // 开启@NotAuthentication不需要token认证
            if (notAuthentication != null) {
                return super.preHandle(request, response, handler);
            }

            String token = request.getHeader(tokenHeader);
            if (StringUtils.isEmpty(token)) {
                throw new TokenVerifyException(PermissionEnum.VERIFY_ERROR);
            }
            // 验证token
//            tokenHelper.verifyToken(token);
        } catch (Exception e) {
            response.setContentType("application/json;charset=utf-8");
            response.setCharacterEncoding("utf-8");
            response.getWriter().write(new Gson().toJson(this.writeResponse(e)));
            return Boolean.FALSE;
        }
        return super.preHandle(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        super.afterCompletion(request, response, handler, ex);
    }

    /**
     * token验证失败返回的response
     *
     * @param e
     */
    private BaseResult writeResponse(Exception e) {
        BaseResult result = new BaseResult();
        result.setStatus(PermissionEnum.VERIFY_ERROR.getStatus());
        result.setSuccess(Boolean.FALSE);
        result.setMessage(e.getMessage());
        return result;
    }
}
